package com.ps.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ps.dto.GoodsSalesDTO;
import com.ps.entity.Orders;
import com.ps.entity.User;
import com.ps.mapper.OrderMapper;
import com.ps.mapper.UserMapper;
import com.ps.service.OrderService;
import com.ps.service.ReportService;
import com.ps.service.UserService;
import com.ps.service.WorkspaceService;
import com.ps.vo.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class ReportServiceImpl   implements ReportService {
    private final OrderMapper orderMapper;
    private final OrderService orderService;
    private final UserService userService;
    private final WorkspaceService workspaceService;

    // 获取营业额统计
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        // 创建日期列表
        List<LocalDate> dateList = new ArrayList<>();
        // 将开始日期添加到日期列表中
        dateList.add(begin);
        // 循环遍历日期列表，直到结束日期
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        // 创建营业额列表
        List<Double> turnoverList = new ArrayList<>();
        // 遍历日期列表
        for (LocalDate date : dateList) {
            // 获取开始时间和结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // 创建map，用于查询
            Map mapp = new HashMap<>();
            mapp.put("begin", beginTime);
            mapp.put("end", endTime);
            mapp.put("status", Orders.COMPLETED);
            // 查询营业额
            LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper
                    .ge(Orders::getOrderTime, beginTime)
                    .le(Orders::getOrderTime, endTime)
                    .eq(Orders::getStatus, Orders.COMPLETED)
                    .select(Orders::getAmount);
            List<Map<String, Object>> result = orderMapper.selectMaps(lambdaQueryWrapper);
            Double turnover = result.stream()
                    .mapToDouble(map -> ((Number) map.getOrDefault("amount", 0)).doubleValue())
                    .sum();
        // 如果营业额为空，则设置为0
            turnover = turnover == null ? 0.0 : turnover;

        // 将营业额添加到营业额列表中
            turnoverList.add(turnover);
        }
        // 返回营业额统计对象
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }
    // 获取用户统计
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            // 查询总用户数
            Integer totalUser =userService.lambdaQuery()
                    .le(User::getCreateTime, endTime).count().intValue();

            // 查询新增用户数
            Integer newUser = userService.lambdaQuery()
                    .ge(User::getCreateTime, beginTime)
                    .le(User::getCreateTime, endTime).count().intValue();

            totalUserList.add(totalUser);
            newUserList.add(newUser);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        // 校验参数有效性
        if (begin == null || end == null) {
            throw new IllegalArgumentException("开始日期和结束日期不能为空");
        }
        if (begin.isAfter(end)) {
            throw new IllegalArgumentException("开始日期不能晚于结束日期");
        }

        // 生成日期列表（包含 begin 和 end）
        List<LocalDate> dateList = new ArrayList<>();
        LocalDate currentDate = begin;
        while (!currentDate.isAfter(end)) {
            dateList.add(currentDate);
            currentDate = currentDate.plusDays(1);
        }

        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer orderCount = getOrderCount(beginTime, endTime, null);
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }

        // 统计总和（使用带默认值的 reduce 避免空值异常）
        Integer totalOrderCount = orderCountList.stream().reduce(0, Integer::sum);
        Integer validOrderCount = validOrderCountList.stream().reduce(0, Integer::sum);

        // 计算订单完成率（避免除零异常）
        double orderCompletionRate = totalOrderCount == 0 ? 0.0 : (double) validOrderCount / totalOrderCount;

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }
    private Integer getOrderCount(LocalDateTime begin,LocalDateTime end,Integer status){
       return orderService.lambdaQuery()
                .ge(Orders::getOrderTime,begin)
                .le(Orders::getOrderTime,end)
                .eq(status!=null,Orders::getStatus,status)
                .count().intValue();

    }
    public SalesTop10ReportVO getSalasTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salestop10 = orderMapper.getSalestop10(beginTime, endTime);
        List<String> names = salestop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList=StringUtils.join(names,",");
        List<Integer> numbers = salestop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList=StringUtils.join(numbers,",");
        return SalesTop10ReportVO
                .builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }
    public void exportBusinessData(HttpServletResponse response) {
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        BusinessDataVO totalBusinessData = workspaceService.getBusinessData(
                LocalDateTime.of(dateBegin, LocalTime.MIN),
                LocalDateTime.of(dateEnd, LocalTime.MAX));

        log.info("Total Business Data: {}", totalBusinessData);

        try (InputStream in = new ClassPathResource("template/运营数据报表模板.xlsx").getInputStream();
             XSSFWorkbook excel = new XSSFWorkbook(in)) {

            XSSFSheet sheet = excel.getSheet("Sheet1");

            // 设置报表标题
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

            // 设置报表汇总数据
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(totalBusinessData.getTurnover());
            row.getCell(4).setCellValue(totalBusinessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(totalBusinessData.getNewUsers());

            row = sheet.getRow(4);
            row.getCell(2).setCellValue(totalBusinessData.getValidOrderCount());
            row.getCell(4).setCellValue(totalBusinessData.getUnitPrice());

            // 填充30天的详细数据
            for (int i = 0; i < 30; i++) {
                LocalDate currentDate = dateBegin.plusDays(i);
                LocalDateTime beginTime = LocalDateTime.of(currentDate, LocalTime.MIN);
                LocalDateTime endTime = LocalDateTime.of(currentDate, LocalTime.MAX);

                BusinessDataVO dailyBusinessData = workspaceService.getBusinessData(beginTime, endTime);

                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(currentDate.toString());
                row.getCell(2).setCellValue(dailyBusinessData.getTurnover());
                row.getCell(3).setCellValue(dailyBusinessData.getValidOrderCount());
                row.getCell(4).setCellValue(dailyBusinessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(dailyBusinessData.getUnitPrice());
                row.getCell(6).setCellValue(dailyBusinessData.getNewUsers());
            }
            // 将Excel写入响应流
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
